﻿var $ = layui.$;

var laydate = layui.laydate;
// 渲染
laydate.render({
    elem: '#dateOfBreeding'
});

layui.use(['form', 'jquery'], function () {
    var form = layui.form;
    var $ = layui.jquery;

    $('#addRowBtn').on('click', function () {
        // 获取数据表格和行数
        const table = document.getElementById('dataTable');
        const numRows = table.rows.length;

        // 如果行数超过5，则禁止添加新行
        if (numRows > 1) {
            layer.msg('已达到最大行数限制，不能再添加新行！');
            return;
        }

        var rowCount = $('#dataTable tbody tr').length + 1; // 获取当前行数并加1作为新行的序号

        var newRowHtml = '<tr>' +
            '<td>' + rowCount + '</td>' + // 新增自增序号列
            `<td>
            <div class="select-wrapper">
					<select name="auricle" id="auricle" lay-filter="auricle" lay-verify="required">
						<option value="">耳号</option>
					</select>
			</div>
            </td>` +
            `<td>
            <div class="select-wrapper">
					<select name="firstWithRam" id="firstWithRam" lay-filter="firstWithRam" lay-verify="required" lay-search="">
						<option value="">配种公羊</option>
					</select>
			</div>
            </td>`+
            `<td>
            <div class="select-wrapper">
					<select name="breedingPattern" id="breedingPattern" lay-filter="breedingPattern" lay-verify="required" lay-search="">
						<option value="">配种方式</option>
					</select>
			</div>
            </td>`+
            `<td>
            <div class="select-wrapper">
					<select name="speciesEstrusType" id="speciesEstrusType" lay-filter="speciesEstrusType" lay-verify="required" lay-search="">
						<option value="">种母发情类型</option>
					</select>
			</div>
            </td>`+
            `<td>
                        <input type="text" name="firstScore" id="firstScore" lay-verify="required" autocomplete="off" class="layui-input" style="width:120px" >
            </td>`+
            `<td>
                        <input type="text" name="currentBuilding" id="currentBuilding" lay-verify="required" autocomplete="off" class="layui-input" style="width:120px" readonly>
            </td>`+
            `<td>
                        <input type="text" name="currentField" id="currentField" lay-verify="required" autocomplete="off" class="layui-input" style="width:120px" readonly>
            </td>`+
            `<td>
            <div class="select-wrapper">
					<select name="transferBuilding" id="transferBuilding" lay-filter="transferBuilding" lay-verify="required" lay-search="">
						<option value="">转入栋舍</option>
					</select>
			</div>
            </td>`+
            `<td>
            <div class="select-wrapper">
					<select name="driveField" id="driveField" lay-filter="driveField" lay-verify="required" lay-search="">
						<option value="">转入栏位</option>
					</select>
			</div>
            </td>`+
            `<td>
            <div class="select-wrapper">
					<select name="reproductiveState" id="reproductiveState" lay-filter="reproductiveState" lay-verify="required" lay-search="">
						<option value="">繁殖状态</option>
					</select>
			</div>
            </td>`+
            `<td>
            <input type="date" name="eventDate" id="eventDate">
            </td>`+
            `<td>
            <input type="text" name="weight" id="weight" lay-verify="required" autocomplete="off" class="layui-input" style="width:120px" >
            </td>`+
            '<td style="width:300px"><button class="layui-btn layui-btn-xs" onclick="saveRow(this)">保存</button><br /><br /><button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteRow(this)">删除</button></td>' +
            '</tr>';
        $('#dataTable tbody').append(newRowHtml);
        form.render(); // 重新渲染表单，使新增的输入框生效

        //绑定种母耳号
        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesAllInfo',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    var enumData = res; // 直接使用返回的数据
                    var select = $('#auricle');
                    $.each(enumData, function (index, item) {
                        if (item.sheepType == "种母") {
                            // 使用正确的字段添加选项到下拉框中
                            var option = $('<option>').val(item.earNnumber).text(item.earNnumber);
                            select.append(option);
                        }
                    });

                    // 添加 lay-search 属性
                    select.attr('lay-search', '');

                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        //绑定种公耳号
        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesAllInfo',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    var enumData = res; // 直接使用返回的数据
                    var select = $('#firstWithRam');
                    $.each(enumData, function (index, item) {
                        if (item.sheepType == "种公") {
                            // 使用正确的字段添加选项到下拉框中
                            var option = $('<option>').val(item.earNnumber).text(item.earNnumber);
                            select.append(option);
                        }
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        //绑定配种方式
        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/ProduceGetRout/api/BreedingMotherRead/GetBreedingPattern',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    var enumData = res; // 直接使用返回的数据
                    var select = $('#breedingPattern');
                    $.each(enumData, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.name).text(item.name);
                        select.append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        //绑定种母发情类型
        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/ProduceGetRout/api/BreedingMotherRead/GetSpeciesEstrusType',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    var enumData = res; // 直接使用返回的数据
                    var select = $('#speciesEstrusType');
                    $.each(enumData, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.name).text(item.name);
                        select.append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        //绑定繁殖状态
        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/ProduceGetRout/api/BreedingMotherRead/GetReproductiveState',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    var enumData = res; // 直接使用返回的数据
                    var select = $('#reproductiveState');
                    $.each(enumData, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.name).text(item.name);
                        select.append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        // 添加change事件监听器
        $('#auricle').change(function () {
            var selectedValue = $(this).val();
            $.ajax({
                url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesGetByEarNumberInfo?EarNumber=' + selectedValue,
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    console.log(res)
                    if (res == undefined) {
                        $("#currentBuilding").val("")
                        $("#currentField").val("")
                    } else {
                        $("#currentBuilding").val(res.cottageId)
                        $("#currentField").val(res.field)
                    }
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        //绑定栋舍
        var data = [];
        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/CootList',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    data = res; // 直接使用返回的数据
                    var select = $('#transferBuilding');
                    $.each(data, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.name).text(item.name);
                        select.append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        // 栋舍栏位二级联动
        $('#transferBuilding').change(function () {
            var name = $("#transferBuilding").val();
            var id = 0;
            $.each(data, function (index, item) {
                if (name == item.name) {
                    id = item.id;
                }
            });
            //监听到了下拉框选择的选项，传递过来
            $.get({
                url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/FieidList', // 后端枚举数据接口地址
                data: {
                    id: id
                },
                dataType: "json",
                success: function (res) {
                    $("#driveField").empty();
                    var option = '<option value=" ">' + "请选择栏位" + '</option>';
                    $("#driveField").append(option);
                    $.each(res, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.name).text(item.name);
                        $('#driveField').append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        updateTableScroll(); // Update table scrolling after adding new row
    });

    function updateTableScroll() {
        // Adjust table scroll after adding new rows
        var tableContainer = $('#dataTable').parent();
        tableContainer.css('overflow-x', 'auto'); // Enable horizontal scrolling
        tableContainer.css('max-width', '100%'); // Ensure table does not exceed parent width
    }
});

// 删除行的函数
function deleteRow(btn) {
    $(btn).closest('tr').remove();
}

function saveRow() {
    var inputValues = {
        personCharge: $("#personCharge").val(),
        dateOfBreeding: $("#dateOfBreeding").val(),
        auricle: $("#auricle").val(),
        breedingPattern: $("#breedingPattern").val(),
        speciesEstrusType: $("#speciesEstrusType").val(),
        firstWithRam: $("#firstWithRam").val(),
        firstScore: $("#firstScore").val(),
        currentBuilding: $("#currentBuilding").val(),
        currentField: $("#currentField").val(),
        transferBuilding: $("#transferBuilding").val(),
        driveField: $("#driveField").val(),
        reproductiveState: $("#reproductiveState").val(),
        eventDate: $("#eventDate").val() == "" ? null : $("#eventDate").val(),
        weight: $("#weight").val() == "" ? null : $("#weight").val(),
    }

    console.log(inputValues)

    // 获取单个字段的输入框元素
    const personCharge = document.getElementById('personCharge');

    if (personCharge.value.trim() === '') {
        layer.msg('负责人不能为空！');
        return;
    }

    // 获取单个字段的输入框元素
    const dateOfBreeding = document.getElementById('dateOfBreeding');

    if (dateOfBreeding.value.trim() === '') {
        layer.msg('配种日期不能为空！');
        return;
    }

    // 获取单个字段的输入框元素
    const auricle = document.getElementById('auricle');

    if (auricle.value.trim() === '') {
        layer.msg('耳号不能为空！');
        return;
    }

    // 获取单个字段的输入框元素
    const firstWithRam = document.getElementById('firstWithRam');

    if (firstWithRam.value.trim() === '') {
        layer.msg('首配公羊不能为空！');
        return;
    }

    // 获取单个字段的输入框元素
    const breedingPattern = document.getElementById('breedingPattern');

    if (breedingPattern.value.trim() === '') {
        layer.msg('配种方式不能为空！');
        return;
    }

    // 获取单个字段的输入框元素
    const speciesEstrusType = document.getElementById('speciesEstrusType');

    if (speciesEstrusType.value.trim() === '') {
        layer.msg('种母发情类型不能为空！');
        return;
    }

    // 在这里您可以执行其他操作，例如发送到服务器端进行处理
    $.ajax({
        type: 'POST',
        url: 'http://10.31.60.18:8000/ProduceSetRout/api/BreedingMother/AddBreedingMother', // 根据实际情况修改ControllerName和ActionName
        data: JSON.stringify(inputValues),
        contentType: "application/json",
        success: function (response) {
            if (response.code == 200) {
                UpdArchives(inputValues)
                layer.msg('添加成功', { icon: 1 }, function () {
                    location.href = '/BreedingMother/BreedingMotherShow'
                });
            } else {
                layer.msg('添加失败');
            }
        },
        error: function (xhr, status, error) {
            // 处理错误响应
            console.error(error);
        }
    });
}

function UpdArchives(inputValues) {
    $.ajax({
        url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesGetByEarNumberInfo?EarNumber=' + inputValues.auricle,
        type: 'get',
        dataType: 'json',
        success: function (data) {
            var values = {
                id: data.id,
                earNnumber: data.earNnumber,
                electronicEarNumber: data.electronicEarNumber,
                sheepBreed: data.sheepBreed,
                sheepGender: data.sheepGender,
                sheepBir: data.sheepBir,
                presence: data.presence,
                growthStage: data.growthStage,
                sheepType: data.sheepType,
                cottageId: inputValues.transferBuilding,
                field: inputValues.driveField,
                reproductiveState: inputValues.reproductiveState,
                pregnancyTest: data.pregnancyTest,
                statusDays: data.statusDays,
                productionGrade: data.productionGrade,
                salesGrade: data.salesGrade,
                geneticGrade: data.geneticGrade,
                birthWeight: data.birthWeight,
                weaningDate: data.weaningDate,
                fatherEarNumber: data.fatherEarNumber,
                motherEarNumber: data.motherEarNumber,
                dayAge: data.dayAge,
                monthAge: data.monthAge,
                weaningAge: data.weaningAge,
                sheepBir: data.sheepBir,
                archivesRemark: data.archivesRemark,
                archivesPicture: data.archivesPicture,
                placeBirth: data.placeBirth,
                inDate: data.inDate
            }

            // 在这里您可以执行其他操作，例如发送到服务器端进行处理
            $.ajax({
                type: 'PUT',
                url: 'http://10.31.60.18:8000/ArchivesSetRout//api/Archives/ArchivesUpdate', // 根据实际情况修改ControllerName和ActionName
                data: JSON.stringify(values),
                contentType: "application/json",
                success: function (response) {
                    console.log(response)
                },
                error: function (xhr, status, error) {
                    // 处理错误响应
                    console.error(error);
                }
            });
        },
        error: function () {
            // 处理 AJAX 请求失败的情况
            console.error('Failed to fetch data for dropdown.');
        }
    });
}